package com.xy.biz.mc.service.impl;

import com.xy.biz.mc.connection.SocketConnection;
import com.xy.biz.mc.service.ConnectionService;
import com.xy.biz.mc.service.PushService;
import com.xy.biz.mc.service.ServerEndPointService;
import com.xy.biz.mc.service.UserConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Objects;

import static com.xy.biz.mc.service.PushService.PREFIX_PUSH_SERVICE;

@Service(PREFIX_PUSH_SERVICE + UserGroupPushServiceImpl.TO_TYPE_USER_GROUP)
public class UserGroupPushServiceImpl implements PushService {

    final static int TO_TYPE_USER_GROUP = 2;

    @Autowired
    private UserConnectionService userConnectionService;
    @Autowired
    private ServerEndPointService serverEndPointService;
    @Autowired
    private ConnectionService connectionService;

    @Override
    public void send(Long messageId, Long toId, byte[] data) {
        Long localServerId = serverEndPointService.getServerId();
        Long userGroupId = toId;
        Map<Long, Long> serverIdMap = userConnectionService.listServerIdByUserGroupId(userGroupId);
        if(!CollectionUtils.isEmpty(serverIdMap)) {
            String text = new String(data);
            Long userId, serverId;
            for(Map.Entry<Long, Long> entry : serverIdMap.entrySet()) {
                userId = entry.getKey();
                serverId = entry.getValue();
                if(Objects.equals(localServerId, serverId)) {
                    SocketConnection socketConnection = connectionService.getConnection(userId);
                    if(socketConnection != null) {
                        socketConnection.sendText(text);
                    }
                }
            }
        }
    }

}
